package top.choviwu.garbage.sort.test;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;
import top.choviwu.garbage.sort.constant.Constants;
import top.choviwu.garbage.sort.entity.Config;
import top.choviwu.garbage.sort.entity.Garbage;
import top.choviwu.garbage.sort.mapper.ConfigMapper;
import top.choviwu.garbage.sort.mapper.GarbageMapper;

import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class SpiderQuaz implements Runnable{

    private static final String URL = "https://sffc.sh-service.com/wx_miniprogram/sites/feiguan/trashTypes_2/Handler/Handler.ashx?a=GET_KEYWORDS&kw=";

    @Autowired
    ConfigMapper configMapper;
    @Autowired
    GarbageMapper garbageMapper;

   private static final   AtomicInteger counter = new AtomicInteger();

   private static final AtomicInteger failCount = new AtomicInteger(0);

//    Config config = configMapper.selectOne(new QueryWrapper().eq(true,"param","garbage_sequeue"));

    public void spider(){
        failCount.set(0);
        String result = Constants.CONFIG.get("garbage_sequeue");
       counter.set(Integer.valueOf(result));
       while (true){
           log.info(">>>>>>>>>>>>>>>Config >>>>>{}",counter.get());
           try {
               HttpResponse response = HttpUtil.createGet(URL+counter.get()).execute();
               log.info("Response Ret >>>>>>{}",response.body());
               if(response.isOk()){
                   Map map = JSONUtil.toBean(response.body(),Map.class);
                   List<String> object  = (List<String>) map.get("kw_arr");
                   if(Objects.isNull(object)){
                       return;
                   }
                   List<Map> list = (List) object;
                   for (int i = 0; i < list.size(); i++) {
                       Map c = list.get(i);
                       Garbage garbage = garbageMapper.selectOne(new QueryWrapper().eq(true,"g_name",(String)c.get("Name")));
                       if(Objects.isNull(garbage)){
                           garbage = new Garbage();
                           garbage.setGName((String)c.get("Name"));
                           garbage.setGTime(LocalDateTime.now());

                           garbage.setGType((String)c.get("TypeKey"));
                           garbageMapper.insert(garbage);
                       }
                   }
               }
           }catch (Exception e){
                log.error(">>>>>>>>>.Error :::>>>{}",e);
               failCount.incrementAndGet();
               log.error(">>>>>>>>>fail count times >>>{}",failCount.get());
               if(failCount.get()>100){
                   log.error(">>>>>>>>>>>>more than 100 times ");
                   return;
               }
           }
           Constants.CONFIG.put("garbage_sequeue",String.valueOf(counter.incrementAndGet()));
           Config config = new Config();
           config.setId(7);
           config.setParam("garbage_sequeue");
           config.setResult(String.valueOf(counter.get()));
           if(configMapper.updateById(config)>0){
               log.info("update success>>>>>>>>>>{}",counter.get());
           }
       }
    }

    @Override
    public void run() {
        spider();
    }

    @Scheduled(cron = "0/30 * * * * ?")
//    @Scheduled(cron = "0 0 0/1 * * ?")
    public void exeSchedule(){
//         Thread thread = new Thread(()->{
//             HttpUtil.createGet("http://localhost:8080/executeSpider").execute();
//         });
//         thread.setDaemon(true);
//         thread.start();
    }
}
